#include "GameObject.h"
#include <Runtime/Resources/ResourceImporter.h>
#include <Runtime/Graphics/Buffer/GraphicsBuffer.h>
#include <Runtime/Application/ApplicationManager.h>
#include <Runtime/Graphics/Device/GraphicsDevice.h>
#include <Runtime/World/CameraManager.h>

GameObject::GameObject() {
	mMesh = std::make_shared<Mesh>();
	mBaseColor = std::make_shared<TextureResource>();
	mEmissive = std::make_shared<TextureResource>();
	mNormal = std::make_shared< TextureResource>();
	mModelMatrix = {
		.World = XMMatrixIdentity(),
		.View = XMMatrixIdentity(),
		.Projection = XMMatrixIdentity()
	};

	GraphicsBufferDesc cbDesc = {};
	cbDesc.ResourceUsage = ResourceUsage::DYNAMIC;
	cbDesc.CPUAccess = BufferCPUAccess::WRITE;
	cbDesc.Usage = BufferUsage::CONSTANT_BUFFER;
	cbDesc.SizeInBytes = sizeof(CBData);
	cbDesc.StructureByteStride = sizeof(XMMATRIX);
	cbDesc.MiscFlags = 0;
	cbDesc.InitialData = &mModelMatrix;
	mGraphicsBuffer = ApplicationManager::GetInstance().GetApplication()->GetDevice()->CreateGraphicsBuffer(cbDesc);
}

void GameObject::UpdateMatrix() {
	auto scaleMat = XMMatrixScaling(mScale.x, mScale.y, mScale.z);
	auto rotMat = XMMatrixRotationRollPitchYaw(XMConvertToRadians(mRotation.x), XMConvertToRadians(mRotation.y), XMConvertToRadians(mRotation.z));
	auto transMat = XMMatrixTranslation(mPosition.x, mPosition.y, mPosition.z);
	mModelMatrix.World = XMMatrixTranspose(scaleMat * rotMat * transMat);
	auto camera = CameraManager::GetInstance().GetCamera();
	mModelMatrix.View = camera->GetViewMatrix();
	mModelMatrix.Projection = camera->GetProjectionMatrix();
}

void GameObject::Update() {
	mRotation.y += 1.0f;
	UpdateMatrix();
}

Helmet::Helmet() {
	mRotation = { 90.0f, 0.0f, 0.0f };

	std::string modelRoot = "C:/Project/3D Learn/glTF-Sample-Models/2.0/DamagedHelmet/glTF/";
	ResourceImporter::ReadStaticMeshFile(modelRoot + "DamagedHelmet.gltf", mMesh);
	ResourceImporter::ReadTextureFile(modelRoot + "Default_albedo.jpg", mBaseColor);
	ResourceImporter::ReadTextureFile(modelRoot + "Default_normal.jpg", mNormal);
	ResourceImporter::ReadTextureFile(modelRoot + "Default_emissive.jpg", mEmissive);
}

Lantern::Lantern() {
	mPosition = {2.0f, 0.0f, 0.0f};
	mScale = { 0.2f, 0.2f, 0.2f };

	std::string modelRoot = "C:/Project/3D Learn/glTF-Sample-Models/2.0/Lantern/glTF/";
	ResourceImporter::ReadStaticMeshFile(modelRoot + "Lantern.gltf", mMesh);
	ResourceImporter::ReadTextureFile(modelRoot + "Lantern_baseColor.png", mBaseColor);
	ResourceImporter::ReadTextureFile(modelRoot + "Lantern_normal.png", mNormal);
	ResourceImporter::ReadTextureFile(modelRoot + "Lantern_emissive.png", mEmissive);
}
